<template>
  <div class="sub-categroy">
    <div class="container">
      <!-- 面包屑 -->
      <sub-bread />
      <!-- 筛选区 -->
      <sub-filter @filterChange="filterChanges" />
      <!-- 商品面板（排序+列表） -->
      <div class="goods-list">
        <sub-sort @sortChange="sortChanges" />
        <ul>
          <li v-for="goods in goodsList" :key="goods.id">
            <goods-item :goods="goods" />
          </li>
        </ul>

        <infinite-loading :loading="loading" :finished="finished" @infinite="getData(requestParams)" />
      </div>

    </div>

  </div>
</template>

<script setup>
import { ref, watchEffect } from "vue";
import SubBread from "./cpns/sub-bread.vue"
import SubFilter from "./cpns/sub-filter.vue";
import SubSort from "./cpns/sub-sort.vue"
import goodsItem from "./cpns/goods-item.vue";
import Category from "@/api/modules/category";
import { useRoute } from "vue-router";

let loading = ref(true)
let finished = ref(false)
let goodsList = ref([])
const route = useRoute()
let requestParams = {
  page: 1,
  pageSize: 20
}
const getData = (requestParams) => {
  loading.value = true
  requestParams.categoryId = route.params.id
  console.log(route.params.id);
  Category.subCategoryGoods(requestParams).then(({ result }) => {

    if (result.items.length) {
      goodsList.value.push(...result.items)
      requestParams.page++
    } else {
      finished.value = true
    }
    loading.value = false

  })
}


watchEffect(() => {
  const newValue = route.params.id
  if (newValue && `/category/sub/${newValue}` == route.path) {
    requestParams.page = 1
    requestParams.pageSize = 20
    finished.value = false
    loading.value = true
    goodsList.value = []
    getData(requestParams)
  }


})
const sortChanges = (sortParams) => {
  finished.value = false
  requestParams = { ...requestParams, ...sortParams }
  requestParams.page = 1
  getData(requestParams)

}
const filterChanges = (filterParams) => {

  finished.value = false
  requestParams = { ...requestParams, ...filterParams }
  requestParams.page = 1
  getData(requestParams)
}

</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;

  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;

    li {
      margin-right: 20px;
      margin-bottom: 20px;

      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
